﻿Imports TNCDAL

Public Class frmPorts_3
    Dim objDataContext As New TanNamChinhDataContext
    Dim arrIndex As New ArrayList
    Dim isInsert As Boolean = True
    Dim posThoat_regularMode_Y As Integer = 171
    Private AddedRowIndex As Integer = -1
    '-------------biến dùng phân trang--------
    Private nRecordsEachPage As Integer = 10
    Public Shared nTotalRow As Integer
    'total rows for next button
    Public Shared pTotalRow As Integer
    'total rows for previous button
    Public Shared nSkippedRows As Integer
    'the steps for skkiping rows for next button
    Public Shared pSkippedRows As Integer
    'the steps for skkiping rows for previous button
    Public Shared Total As Integer
    '-------------hết phần biến dùng phân trang

    Private Sub frmCountry_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'hiển thị danh sách các nước
        BindCboCountry()
        'hiển thị danh sách các cảng
        BindGridPorts()
        'hien thi nut them, xoa, sua, thoat
        HienThiNut_Thuong()
    End Sub
    Private Sub HienThiNut_Thuong()
        dgPorts.AllowUserToAddRows = False
        dgPorts.AllowUserToDeleteRows = False
        dgPorts.ReadOnly = True
        btThem.Visible = True
        btXoa.Visible = True
        btSua.Visible = True
        btLuu.Visible = False
        btHuy.Visible = False
        btThoat.Location = New Point(btThoat.Location.X, posThoat_regularMode_Y)
    End Sub
    Private Sub HienThiNut_Sua()
        btThem.Visible = False
        btXoa.Visible = False
        btSua.Visible = False
        btLuu.Visible = True
        btHuy.Visible = True
        btLuu.Location = New Point(btThem.Location)
        btHuy.Location = New Point(btXoa.Location)
        btThoat.Location = New Point(btThoat.Location.X, btSua.Location.Y)
    End Sub
    Private Sub BindCboCountry()
        Dim cCtrl As New CCountryController()
        Dim countries = cCtrl.SelectAllRecord()
        With cboCountry
            .DataSource = countries
            .DisplayMember = "CountryName"
            .ValueMember = "ID_Country"
        End With
        'Dim emptyTable As tblCountry() = {New tblCountry With {.ID_Country = 0, .CountryName = "-------"}}
        'Dim countries2 = (From e In emptyTable Select e).Union(From c In cCtrl.SelectAllRecord
        '                  Select c).ToList
        'With cboSearchCountries
        '    .DataSource = countries2
        '    .DisplayMember = "CountryName"
        '    .ValueMember = "ID_Country"
        'End With
    End Sub
    Private Sub BindGridPorts(Optional ByVal sPort As String = "", Optional ByVal idCountry As Integer = -1)
        Dim pCtrl As New CPortController()
        'Dim Rowss = pCtrl.SelectRecords(sPort, idCountry) '.OrderBy(Function(p) p.Port)
        Dim Rowss = pCtrl.SelectAllRecord()
        'If (sPort <> "") Then
        '    Rowss = Rowss.Where(Function(p) p.Port.StartsWith(sPort))
        'End If
        'If (idCountry > 0) Then
        '    Rowss = Rowss.Where(Function(p) p.ID_Country = idCountry)
        'End If
        dgPorts.DataSource = Rowss
        dgPorts.Columns.Remove("tblCountry")
        'nTotalRow = Rowss.Count()
        'pTotalRow = Rowss.Count()
        'Total = Rowss.Count()
        'If (Total <= nRecordsEachPage) Then
        '    dgPorts.DataSource = Rowss
        'Else
        '    nSkippedRows = nRecordsEachPage
        '    Dim nr = Rowss.Take(nSkippedRows)
        '    dgPorts.DataSource = nr
        '    'calculate the remaining rows for next button
        '    nTotalRow = nTotalRow - nSkippedRows
        'End If
    End Sub

    Private Sub btThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btThoat.Click
        Me.Close()
    End Sub

    Private Sub btXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btXoa.Click
        Dim sName As String = dgPorts.CurrentRow.Cells(1).Value.ToString
        If (MessageBox.Show("Bạn có chắc muốn xoá " + sName + " ?", "Xác nhận", MessageBoxButtons.YesNo) = vbYes) Then
            Dim id As Integer = Integer.Parse(dgPorts.CurrentRow.Cells(0).Value.ToString)
            'remove ra khoi datagridview
            dgPorts.Rows.Remove(dgPorts.CurrentRow)
            'xoa khoi du lieu
            Dim cCtrl As New CPortController()
            cCtrl.DeleteRecord(id)
        End If
    End Sub

    Private Sub btLuu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btLuu.Click
        'luu du lieu 
        Dim cCtrl As New CPortController(objDataContext)
        For Each i As Integer In arrIndex
            Dim sName As String = dgPorts.Rows(i).Cells(1).Value.ToString
            Dim c As tblPort
            If (isInsert) Then
                c = New tblPort
                c.Port = sName
                c.ID_Country = dgPorts.Rows(i).Cells(2).Value
                Dim newId As Integer = cCtrl.InsertRecord(c)
                dgPorts.Rows(i).Cells(0).Value = newId
            Else
                Dim id As Integer = Integer.Parse(dgPorts.Rows(i).Cells(0).Value.ToString)
                c = cCtrl.SelectRecordByID(id)
                c.Port = sName
                c.ID_Country = dgPorts.Rows(i).Cells(2).Value
                cCtrl.UpdateRecordWithoutAttach(c)
            End If
        Next
        'tro ve trạng thái thường
        HienThiNut_Thuong()
    End Sub

    Private Sub dgCountries_CellBeginEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles dgPorts.CellBeginEdit
        If Not dgPorts.Rows(e.RowIndex).IsNewRow Then
            If e.RowIndex < dgPorts.NewRowIndex Then
                If AddedRowIndex <> e.RowIndex Then
                    e.Cancel = True
                End If
            End If
        End If
    End Sub

    Private Sub dgCountries_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgPorts.CellEndEdit
        If (String.IsNullOrEmpty(dgPorts.Rows(e.RowIndex).ErrorText)) Then
            If (Not arrIndex.Contains(e.RowIndex)) Then
                arrIndex.Add(e.RowIndex)
            End If
        Else
            dgPorts.Rows(e.RowIndex).ErrorText = String.Empty
        End If

    End Sub

    Private Sub dgCountries_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles dgPorts.CellValidating
        Try
            'kiem tra truong hop them moi thi co bi trung ten hay khong
            Dim sName As String = e.FormattedValue.ToString()
            If (CheckNameExist(sName, e.RowIndex)) Then
                'dgCountries.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = String.Empty
                dgPorts.Rows(e.RowIndex).ErrorText = "Cảng này đã có!"
                MessageBox.Show("Cảng này đã có. Nhấn ESC để nhập lại!")
                e.Cancel = True
            End If
        Catch ex As Exception
        End Try
    End Sub

    Private Sub dgCountries_UserAddedRow(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) Handles dgPorts.UserAddedRow
        AddedRowIndex = dgPorts.NewRowIndex - 1
    End Sub
    Private Sub btThem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btThem.Click
        dgPorts.AllowUserToAddRows = True
        dgPorts.ReadOnly = False
        arrIndex.Clear()
        isInsert = True
        HienThiNut_Sua()
    End Sub
    Private Sub btSua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btSua.Click
        dgPorts.ReadOnly = False
        dgPorts.AllowUserToAddRows = False
        arrIndex.Clear()
        isInsert = False
        HienThiNut_Sua()
    End Sub

    Private Sub btHuy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btHuy.Click
        'hien thi lai trang thai binh thuong
        HienThiNut_Thuong()
        'lay lai du lieu cu
        BindCboCountry()
        BindGridPorts()
    End Sub
    Private Function CheckNameExist(ByVal sName As String, ByVal index As Integer) As Boolean
        For Each row As DataGridViewRow In dgPorts.Rows
            If (row.Index <> index) Then
                Dim cName As String = row.Cells(1).Value.ToString
                If (sName.ToLower = cName.ToLower) Then
                    Return True
                End If
            End If
        Next
        Return False
    End Function

    Private Sub btPrev_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btPrev.Click
        'Dim pCtrl As New CPortController
        'Dim sPort As String = txtSearchPortName.Text
        'Dim idCountry As Integer = CType(cboSearchCountries.SelectedItem, tblCountry).ID_Country
        'If ((Total - pTotalRow) - nRecordsEachPage = 0) OrElse Total - pTotalRow = 0 Then
        '    Dim Rowss = pCtrl.SelectAllRecord.OrderBy(Function(p) p.Port)
        '    If (sPort <> "") Then
        '        Rowss = Rowss.Where(Function(p) p.Port.StartsWith(sPort))
        '    End If
        '    If (idCountry > 0) Then
        '        Rowss = Rowss.Where(Function(p) p.ID_Country = idCountry)
        '    End If
        '    Rowss = Rowss.Take(nRecordsEachPage)
        '    dgPorts.DataSource = Rowss
        '    nTotalRow += nRecordsEachPage

        '    nSkippedRows -= nRecordsEachPage

        '    If nSkippedRows = 0 Then
        '        nSkippedRows = nRecordsEachPage
        '    End If

        '    'calculate total rows for previous button
        '    pTotalRow += nRecordsEachPage
        '    btPrev.Enabled = False
        '    btNext.Enabled = True
        'ElseIf Total - pTotalRow > nRecordsEachPage Then

        '    Dim Rowss = (pCtrl.SelectAllRecord.OrderBy(Function(p) p.Port))
        '    If (sPort <> "") Then
        '        Rowss = Rowss.Where(Function(p) p.Port.StartsWith(sPort))
        '    End If
        '    If (idCountry > 0) Then
        '        Rowss = Rowss.Where(Function(p) p.ID_Country = idCountry)
        '    End If
        '    Rowss = Rowss.Skip(Total - pTotalRow - nRecordsEachPage).Take(nRecordsEachPage)
        '    dgPorts.DataSource = Rowss

        '    btNext.Enabled = True
        '    pTotalRow += nRecordsEachPage
        '    nTotalRow = nTotalRow + nRecordsEachPage

        '    nSkippedRows -= nRecordsEachPage
        'End If
    End Sub

    Private Sub btNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btNext.Click
        'Dim pCtrl As New CPortController
        'Dim sPort As String = txtSearchPortName.Text
        'Dim idCountry As Integer = CType(cboSearchCountries.SelectedItem, tblCountry).ID_Country
        'If nTotalRow <= nRecordsEachPage Then

        '    Dim Rowss = (pCtrl.SelectAllRecord.OrderBy(Function(p) p.Port))
        '    If (sPort <> "") Then
        '        Rowss = Rowss.Where(Function(p) p.Port.StartsWith(sPort))
        '    End If
        '    If (idCountry > 0) Then
        '        Rowss = Rowss.Where(Function(p) p.ID_Country = idCountry)
        '    End If
        '    Rowss = Rowss.Skip(nSkippedRows).Take(nTotalRow)
        '    dgPorts.DataSource = Rowss
        '    pTotalRow -= nRecordsEachPage
        '    'now added
        '    nSkippedRows += nRecordsEachPage
        '    nTotalRow -= nRecordsEachPage            '
        '    btNext.Enabled = False
        '    btPrev.Enabled = True
        'ElseIf nTotalRow > nRecordsEachPage Then

        '    Dim Rowss = (pCtrl.SelectAllRecord.OrderBy(Function(p) p.Port))
        '    If (sPort <> "") Then
        '        Rowss = Rowss.Where(Function(p) p.Port.StartsWith(sPort))
        '    End If
        '    If (idCountry > 0) Then
        '        Rowss = Rowss.Where(Function(p) p.ID_Country = idCountry)
        '    End If
        '    Rowss = Rowss.Skip(nSkippedRows).Take(nRecordsEachPage)
        '    dgPorts.DataSource = Rowss
        '    pTotalRow -= nRecordsEachPage

        '    nTotalRow = nTotalRow - nRecordsEachPage
        '    nSkippedRows += nRecordsEachPage

        '    btPrev.Enabled = True
        'End If
    End Sub

    Private Sub txtSearchPortName_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearchPortName.TextChanged
        Dim id As Integer = -1
        Try
            id = CType(cboSearchCountries.SelectedItem, tblCountry).ID_Country
        Catch ex As Exception
        End Try
        BindGridPorts(txtSearchPortName.Text, id)
    End Sub

    Private Sub cboSearchCountries_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboSearchCountries.SelectedIndexChanged
        Try
            Dim id As Integer = CType(cboSearchCountries.SelectedItem, tblCountry).ID_Country
            BindGridPorts(txtSearchPortName.Text, id)
        Catch ex As Exception
        End Try

    End Sub
End Class